import type { Router } from 'vue-router'
import LayoutView from '@/layout/index.vue'
import { usePermissionStore } from '@/store/modules/permissions'

// 根据权限动态生成路由表
export function generateRouter(router: Router) {
  return new Promise((resolve) => {
    const permissionStore = usePermissionStore()
    const filterPerm = permissionStore.permList.filter(
      item => item.permType === 1,
    )
    const modules = import.meta.glob('@/views/**/*.vue')
    const listRouter = filterPerm.map((item) => {
      return {
        component: () => {
          try {
            const curComponent = modules[`/src/views${item.path}/index.vue`]
            const cmptPromise = curComponent().then(
              (result: any) => {
                const def = result.default
                def.name = def.__name = `${item.path}/}`
                return result
              },
            )
            return cmptPromise
          }
          catch (error) {
            // eslint-disable-next-line no-console
            console.log(error)
            return import(`@/views/notFound/404.vue`)
          }
        },
        children: [],
        path: item.path,
        name: item.name,
        meta: {
          icon: item.icon,
          title: item.name,
        },
      }
    })

    router.addRoute({
      path: '/layout',
      name: 'Layout',
      component: LayoutView,
      children: listRouter,
      redirect: ``,
      meta: {
        icon: 'layout',
        title: '布局',
      },
    })

    permissionStore.updateIsGenerated(true)
    resolve(listRouter)
  })
}
